<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\handlers\backend;

use common\helper\App;
use common\models\Admin;
use common\handlers\BaseHandler;
use yii\web\Response;

/**
 * 检查站点开关
 * @author cleverstone
 * @since ym2.0
 */
class BeforeActionValidateSite extends BaseHandler
{
    /**
     * @param \yii\base\ActionEvent $event
     * @throws \Throwable
     */
    public function run($event)
    {
        $siteSwitch = $this->setting->read('SYS.SYS_PROTECT', 0);

        $loginRoute = App::params('admin.route.login');
        $currentRoute = $event->action->controller->route;

        if ($siteSwitch && strcasecmp($currentRoute, $loginRoute)) {
            $user = $this->user;
            if (!$user->isGuest) {
                /** @var Admin $identity */
                $identity = $user->identity;
                // 拥有者不检查
                if ($identity->group == Admin::ADMIN_GROUP) {
                    return;
                }

                $user->logout();
            }

            $siteCloseTips = $this->setting->read('SYS.SYS_PROTECT_TIPS', '站点临时维护, 工程师正在全力抢修中...');

            $response = $this->response;
            if ($this->request->isAjax) {
                $response->format = Response::FORMAT_JSON;
                $response->data = [
                    'code' => App::params('http.res.failure'),
                    'msg' => $siteCloseTips,
                ];
            } else {
                $response->redirect([$loginRoute]);
            }

            $this->session->setFlash(App::params('admin.session.flash.error'), $siteCloseTips);

            $event->isValid = false;
            $event->handled = true;
        }
    }
}